/**
 * @author Nicolas Lusa (lusan@usi.ch)
 * @author Nicolas Zimerman (zimerman@usi.ch)
 * @author Nicolas Latorre (nicolas.latorre@usi.ch)
 */
package ch.usi.inf.pf2.gui.action;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import ch.usi.inf.pf2.LogicSim;
import ch.usi.inf.pf2.circuit.Circuit;
import ch.usi.inf.pf2.circuit.Component;
import ch.usi.inf.pf2.circuit.Input;
import ch.usi.inf.pf2.circuit.Value;
import ch.usi.inf.pf2.file.interaction.InstructionReader;
import ch.usi.inf.pf2.gui.CircuitFrame;
import ch.usi.inf.pf2.gui.Model;
import ch.usi.inf.pf2.time.Schedule;
import ch.usi.inf.pf2.time.SetValueOfInputEvent;

public final class LoadAction extends AbstractAction {
	
	private static final long serialVersionUID = -8927019379012692064L;
	private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
    private CircuitFrame circuitFrame;
    private ArrayList<Component> currentCircuit;
    private final Model model;
    
    
    public LoadAction(final CircuitFrame circuitFrame, final Model model) {
    	this.circuitFrame = circuitFrame;
    	this.model = model;
        currentCircuit = new ArrayList<Component>();
        putValue(NAME, "Load");
        final ImageIcon icon = new ImageIcon(getClass().getResource("../icons/open.png"));
        putValue(SMALL_ICON, icon);
        putValue(SHORT_DESCRIPTION, "Load a file from the local machine.");

        setEnabled(true);
    }
    
    /**
     * Open function: open a file chooser to select a new file,
     * and then display the circuit.
     */
    public void actionPerformed(final ActionEvent ev) {
    	int returnVal = fileChooser.showOpenDialog(circuitFrame); 

        if(returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File selectedFile = fileChooser.getSelectedFile();
        InstructionReader reader = new InstructionReader(selectedFile.getAbsolutePath());
 
        currentCircuit = reader.getCircuit();
        
        if(currentCircuit == null) {
            JOptionPane.showMessageDialog(circuitFrame,
                    "The file was not in a recognized file format.",
                    "File Load Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        
        
        if(circuitFrame.getModel().getCircuit().getShapes().size() == 0) {
        	for(Component c : currentCircuit) {
        		circuitFrame.getModel().getCircuit().add(c);
        	}
        	ResetAction.reset(circuitFrame, model);
        }
        else {
        	Circuit circuit = new Circuit(currentCircuit);
            Model model = new Model(circuit);
            Schedule.resetStep();
    		ResetAction.reset(circuitFrame, model);
        	LogicSim logicSim = new LogicSim(model);

        }
    } 
}
